<template>
    <fieldset>
        <legend>购物车</legend>
        <ul>
            <li v-for="item in carts">
                <b>产品名称：{{ item.title }}</b>
                &nbsp; &nbsp;
                <b>价格：{{ item.price }}</b>
                &nbsp; &nbsp;
                <b>数量：{{ item.count }}</b>
                &nbsp; &nbsp;
                <button @click="jian(item)">-</button>
            </li>
        </ul>
        <h1>总价：{{total}}</h1>
    </fieldset>
</template>


<script setup>
import { cart } from "../../store/cart.js"
import { storeToRefs } from "pinia"
import { user } from "../../store/products"

let userStore = user()
let { products } = storeToRefs(userStore)

let cartStore = cart()
let { carts,total } = storeToRefs(cartStore)

let jian = (item) => {
    let target = cartStore.carts.find(p => p.id == item.id)
    if (target) {
        target.count--
    }
    let th = userStore.products.find(t=>t.id == item.id)
    if(th){
        th.inventory++
    }
    if (target.count == 0) {
        cartStore.carts = cartStore.carts.filter(p => p.id !== target.id)
    }

}

</script>